import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import { setupDirectives } from './utils/directives'

import { initUserState, fetchUserInfo, clearUserState } from './utils/userStore'
import axios from "axios";
import { bootstrapSocketAutoReconnect } from './utils/socketBootstrap'





// 配置axios默认值
axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL || '/api'
axios.defaults.timeout = 10000

// 添加请求拦截器，自动添加token
axios.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 添加响应拦截器，处理token过期等情况
axios.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response && (error.response.status === 401 || error.response.status === 403)) {
      // token过期或无效，清除本地存储并跳转到登录页
      clearUserState()
      router.push('/login')
    }
    else if (error.response && error.response.status === 403) {
      clearUserState()
      router.push('/login')
    }

    return Promise.reject(error)
  }
)

// 初始化用户状态
initUserState()

// 如果有token，尝试获取用户信息
const token = localStorage.getItem('token')
if (token) {
  fetchUserInfo()
}
// 控制是否启用全局 Socket 自动重连，默认关闭
const enableSocket = import.meta.env.VITE_ENABLE_SOCKET === 'true'
if (enableSocket) {
  bootstrapSocketAutoReconnect()
}
const app = createApp(App)

// 注册所有图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

// 注册自定义指令
setupDirectives(app)

app.use(router)
app.use(ElementPlus)
app.mount('#app') 